﻿/** ********定义实体控制器********** */

var Entry_Controller = Class.create();

Entry_Controller.prototype = {
	// 对象初始化
	initialize : function(target, options) {
		THIS = this;
		controller = $(target);
		this.options = options;
		this.locations = new Array();
		this.ENTRY = {
			KEY_POINT : 0,
			VEHICLE : 1,
			ROAD : 2,
			LIGHTS : 3
		};
		this.OPTERATION = {
			UPDATE : 99,
			BASIC : 98,
			MAP_EDITOR : 97,
			STATIC_BLOCK : 96,
			DYNAMIC_BLOCK : 95
		};
	},
	post_ajax_then_do : function(url, params, callback) {
		ajax_post(url, params, function(msg) {
			if (msg != '' && msg != null) {
				callback(msg);
			}
		});

	},
	query_exist_roads : function(url, params) {
		ajax_post(url, params, function(msg) {
			if (msg != '' && msg != null) {
				var json = eval("(" + msg + ")");
				THIS.update_current_road_by_json(json);
			}
		});
	},
	// 根据后台保存的数据重构前台路径
	update_current_road_by_json : function(json) {
		var index = 0;
		roads = new ArrayList();
		for ( var ri in json) {
			var road = json[ri];
			roads.cur = parseInt(ri);
			roads.add(new Road({
				id : road.id,
				name : road.name,
				color : '#abc',
			}));
			var points = road.point;
			var locs = new ArrayList();
			for ( var pi in points) {
				var p = points[pi];
				var loc = new Location(p.x, p.y);
				loc.id = p.id;
				loc.area = cur_area;
				locs.add(loc);
				THIS.addEntry(THIS.OPTERATION.UPDATE, loc, controller, index);
				index++;
			}
			roads.get(roads.cur).locs = locs;
		}
	},
	detect_toolbar_operation : function(toolbar_selector) {
		var tp = $("#tool_options");
		tp.html("");
		// 初始化选项板
		switch (toolbar_selector.val()) {
		// 构建道路
		case 'construct_road':
			$("#submit_all").val("提交所有道路信息");
			currentOperation = THIS.ENTRY.ROAD;
			THIS.fresh_toolbar_construct_road(tp);
			break;
		// 标注关键点
		case 'construct_key_point':
			$("#submit_all").val("提交所有道路信息");
			currentOperation = THIS.ENTRY.KEY_POINT;
			break;
		// 构建其他实体
		case 'construct_other_entry':
			THIS.fresh_toolbar_other_entry(tp);
			break;
		default:
			;
			break;
		}
	},
	add_Light_Nodes : function(node) {
		for ( var i = 0; i < 16; i++) {
			if (i == 1) {
				node += "<div id='n1' index='0' class='light_button' >n1</div>";
			} else if (i == 2) {
				node += "<div id='n2' index='1' class='light_button' >n2</div>";
			} else if (i == 4) {
				node += "<div id='w2' index='7' class='light_button'>w2</div>";
			} else if (i == 7) {
				node += "<div id='e1' index='2' class='light_button'>e1</div>";
			} else if (i == 8) {
				node += "<div id='w1' index='6'class='light_button'>w1</div>";
			} else if (i == 11) {
				node += "<div id='e2' index='3' class='light_button'>e2</div>";
			} else if (i == 13) {
				node += "<div id='s2' index='5' class='light_button'>s2</div>";
			} else if (i == 14) {
				node += "<div id='s1' index='4' class='light_button'>s1</div>";
			} else {
				node += "<div id='light"
						+ i
						+ "' style='float:left;height:20px;width:20px;text-align:center;'>&nbsp;&nbsp</div>";
			}
			if ((i + 1) % 4 == 0)
				node += "<br><br>";
		}
		node += "<button id='add_lights'>添加红绿灯</button>";
		return node;
	},
	show_all_lights : function() {

	},
	add_Lights_Event : function() {
		$(".light_button").click(function() {
			$(this).toggleClass("grey");
		});
		$("#add_lights").click(function() {
			Lights = Lights ? Lights : new ArrayList();
			Lights.add(jQuery.extend(true, {}, lig));
			$(".light_button").removeClass("grey");
			$(".light_button").removeClass("green");
			lig=new Light();
		});
	},
	fresh_toolbar_other_entry : function(tp) {
		if (!tp)
			tp = $("#tool_options");
		tp.html("");
		if (roads.size() && roads.get(0).locs.size()) {
			var node = "<p><select id='other_entry' value='3'>"
					+ "<option value='3'>红绿灯</option>" + "</select></p>";
			tp.append(THIS.add_Light_Nodes(node));
			THIS.add_Lights_Event();
			Lights = (!Lights) ? Lights : new ArrayList();
			$("#submit_all").val("提交所有红绿灯信息");
			currentOperation = THIS.ENTRY.LIGHTS;
			$("#other_entry").change(function() {
				switch (parseInt($(this).val())) {
				case THIS.ENTRY.LIGHTS:
					$("#submit_all").val("提交所有红绿灯信息");
					currentOperation = $(this).val();
					tp.html(node);
					tp.append(THIS.add_Light_Nodes(node));
					break;
				}
			});
		} else {
			var node = "<p style='color:red;'>请先创建道路</p>";
			tp.append(node);
		}
	},
	fresh_toolbar_construct_road : function(tp) {
		if (!tp)
			tp = $("#tool_options");
		tp.html("");
		if (roads.cur != -1 && roads.cur != undefined) {
			// 已存在道路时
			// 显示存在道路
			var node = "<p>当前道路:<select type='text' maxlength='60' id='road_name'>";

			for ( var index = 0; index < roads.size(); index++) {
				var r = roads.get(index);
				if (parseInt(index) == roads.cur) {
					node += "<option value='" + index
							+ "' selected='selected'>" + r.name + "</option>";
				} else {
					node += "<option value='" + index + "'>" + r.name
							+ "</option>";
				}
			}

			node += "</select></p><p>道路名称：<input type='text' id='road_name_"
					+ roads.cur
					+ "' style='width:100px;' value='"
					+ roads.get(roads.cur).name
					+ "'/><input type='button' value='X' id='delete_road'/></p>";
			var road_name = $(node);
			var show_road = $("道路关键点:<div class='show_road' id='show_road_"
					+ roads.cur + "'>当前未选择道路关键点，请创建或者选择关键点</div>");
			var road_color = $("<p>道路颜色:<input type='text' maxlength='60' id='road_color_"
					+ roads.cur + "' value='" + roads.get(0).color + "'/></p>");
			var modify_ok = $("<p><input type='button' value='确认修改' id='ensure_modify'/><input type='button' value='创建新道路' id='create_road'/></p>");
			tp.append(road_name);
			tp.append(show_road);
			tp.append(road_color);
			tp.append(modify_ok);
			$("#road_name_" + roads.cur).attr("checked", "cheched");
			// 重新调整关键点颜色
			var kps = $(".key_point");
			kps.removeClass("selected");
			var cl = roads.get(roads.cur).locs;
			for ( var l = 0; l < cl.size(); l++) {
				for ( var i in kps) {
					if (parseInt(kps.eq(i).attr("x")) == cl.get(l).x
							&& parseInt(kps.eq(i).attr("y")) == cl.get(l).y) {
						kps.eq(i).addClass("selected");
					}
				}
			}
			// 填充内容
			roads.get(roads.cur).showRoadsIn($("#show_road_" + roads.cur));
			// 选择某条道路
			$("#road_name").change(function() {
				roads.cur = parseInt($(this).val());
				THIS.fresh_toolbar_construct_road(tp);
			});
		} else {
			// 没有道路时
			roads = new ArrayList();
			roads.cur = 0;
			roads.add(new Road({
				id : 0,
				name : '默认道路0',
				color : '#abc'
			}));
			var road_name = $("<p>道路名称:<input type='text' maxlength='60' id='road_name_"
					+ roads.cur
					+ "' style='width:100px;' value='"
					+ roads.get(roads.cur).name
					+ "'/><input type='button' value='X' id='delete_road'/></p>");
			var show_road = $("道路关键点:<div class='show_road' id='show_road_"
					+ roads.cur + "'>当前未选择道路关键点，请创建或者选择关键点</div>");
			var road_color = $("<p>道路颜色:<input type='text' maxlength='60' id='road_color_"
					+ roads.cur
					+ "' value='"
					+ roads.get(roads.cur).color
					+ "'/></p>");
			var modify_ok = $("<p><input type='button' value='确认修改' id='ensure_modify'/><input type='button' value='创建新道路' id='create_road'/></p>");
			tp.append(road_name);
			tp.append(show_road);
			tp.append(road_color);
			tp.append(modify_ok);
		}
		// 添加节点
		// 添加事件
		// 创建新道路
		$("#create_road").click(function() {
			roads.cur = roads.size();
			roads.add(new Road({
				id : 0,
				name : '默认道路' + roads.size(),
				color : '#abc'
			}));
			THIS.fresh_toolbar_construct_road(tp);
		});
		// 删除某条路
		$("#delete_road").click(
				function() {
					var cr = roads.get(roads.cur);
					if (confirm("要删除\"" + cr.name + "\"?")) {
						THIS.post_ajax_then_do(HOST + "delete_road_by_id",
								"id=" + cr.id, function(msg) {
									if (msg == "" || msg == null)
										return;

									if (roads.size() == 1) {
										cr.name = '默认道路0';
										cr.color = '#abc';
										cr.locs = new ArrayList();
										THIS.fresh_toolbar_construct_road(tp);
										return;
									}
									roads.remove(roads.cur);
									roads.cur = roads.size() - 1;
									// roads.length=roads.length>1?roads.length-1:0;
									THIS.fresh_toolbar_construct_road(tp);
								});
					}

				});
		// 修改道路基本信息
		$("#ensure_modify").click(function() {
			var r = roads.get(roads.cur);
			var rname = $("#road_name_" + roads.cur).val();
			var rcolor = $("#road_color_" + roads.cur).val();
			if (rname == '' || rcolor == '')
				return;
			if (confirm("确认修改道路:\"" + r.name + "\"?")) {
				r.name = rname;
				r.color = rcolor;
				THIS.fresh_toolbar_construct_road(tp);
			}
		});

	},
	// 设置默认属性
	SetOptions : function(options) {
		this.options = { // 默认值
		};
		Object.extend(this.options, options || {});
	},
	// 添加实体（关键点/其他实体）
	addEntry : function(type, loc, parent, index) {
		switch (type) {
		case this.OPTERATION.UPDATE:
		case this.OPTERATION.BASIC:
		case this.ENTRY.KEY_POINT:
			var _kp_ = $("#kp" + loc.id);
			if (_kp_.size() != 0)
				return;
			var kp = $("<div class='key_point round"
					+ $("#sample_key_point").width() / 2 + "' id='kp_" + loc.id
					+ "' value='" + loc.id + "'>"+(DEBUG?loc.id:"")+"</div>");
			parent.append(kp);
			kp.attr({
				x : loc.x,
				y : loc.y,
				id : "kp_" + (loc.id ? loc.id : 0)
			});
			kp.css({
				position : "absolute",
				'top' : (loc.y - TOP + controller.offset().top - Math.floor(kp
						.width() / 2)),
				'left' : (loc.x - LEFT + controller.offset().left - Math
						.floor(kp.height() / 2)),
				'z-index' : 3
			});
			kp.click(function() {
				THIS.addEntryEvent(type, $(this));
			});
			kp.mouseout(function() {
				$(this).removeClass("red");
			}).mouseover(function() {
				$(this).addClass("red");
			});
			break;
		case this.ENTRY.ROAD:

			break;
		}
	},
	addEntryEvent : function(type, cur) {
		switch (currentOperation) {
		// 标注关键点时，单击关键点为删除
		case THIS.ENTRY.KEY_POINT:
			if (cur.attr("class").indexOf("selected") > -1) {
				alert("需要删除当前关键点，请先将其从道路中剔除");
				deleting = true;
				return;
			}

			removeIt = true;

			roads.foreach(function(index, data, handler) {
				data.locs.foreach(function(i, d, handler) {
					if (d.id == parseInt(handler.attr("value"))) {
						alert("需要删除当前关键点，请先将其从道路中剔除");
						deleting = true;
						removeIt = false;
						return;
					}
				}, handler);
			}, cur);

			if (!removeIt) {
				removeIt = true;
				return;
			}

			delete THIS.locations[parseInt(cur.attr("value"))];
			THIS.locations.length = THIS.locations.length >= 1 ? THIS.locations.length - 1
					: 0;
			cur.remove();
			deleting = true;
			break;
		// 构建道路时，单击关键点表示选中，添加至某条道路中
		case THIS.ENTRY.ROAD:
			cur.toggleClass("selected");
			var x = parseInt(cur.attr('x'));
			var y = parseInt(cur.attr('y'));
			var loc = new Location(x, y);
			loc.id = cur.attr("point_id") ? cur.attr("point_id") : 0;
			roads.get(roads.cur).addKeyPointToRoad(
					loc,
					function(list) {
						var sr = $("#show_road_" + roads.cur);
						sr.html("");
						list.foreach(function(index, data) {
							index != list.size() - 1 ? sr.append("(" + data.x
									+ "," + data.y + ")>") : sr.append("("
									+ data.x + "," + data.y + ")");
						});
					});
			break;
		case THIS.OPTERATION.BASIC:
			deleting = true;
			break;
		case THIS.ENTRY.LIGHTS:
			var x = parseInt(cur.attr('x'));
			var y = parseInt(cur.attr('y'));
			var loc = new Location(x, y);
			loc.id = parseInt(cur.attr("value"));
			if (cur.attr("class").indexOf("purple") > 0) {
				// 删除红绿灯
				lig.locs.foreach(function(index, data, l) {
					if (l.id == data.id) {
						l.x = -1;
						l.y = -1;
						lig.locs.setElementAt(index, l);
					}
				}, loc);
				lig.color($(".light_button"));
			} else {
				// 添加红绿灯
				if (typeof (lig) == 'undefined')
					lig = new Light();
				$(".light_button").each(
						function() {
							var i = parseInt($(this).attr("index"));
							if ($(this).attr("class").indexOf("grey") > 0
									&& i == lig.locs.size()) {
								lig.locs.addElementAt(i, new Location(-1, -1));
								lig.locs.addElementAt(i + 1, new Location(-1,
										-1));
							}
						});
				var e = false;
				lig.locs.foreach(function(index, data, l) {
					if (l.id == data.id && l.id != 0) {
						e = true;
					}
				}, loc);
				if (!e)
					lig.add(loc);
				lig.color($(".light_button"));
			}
			cur.toggleClass("purple");
			if (cur.attr("isLight"))
				cur.attr("isLight", "true");
			else
				cur.removeAttr("isLight");
			break;
		}
	}

};